package com.ego.rabbitmq.lintener;


import com.ego.commons.exception.DaoException;
import com.ego.commons.pojo.BigAd;
import com.ego.commons.pojo.OrderPojo;
import com.ego.commons.utils.HttpClientUtil;
import com.ego.commons.utils.IDUtils;
import com.ego.commons.utils.JsonUtils;
import com.ego.commons.utils.ServletUtil;
import com.ego.dubbo.service.TBContentDubboService;
import com.ego.dubbo.service.TBItemDubboService;
import com.ego.dubbo.service.TbOrderDubboService;
import com.ego.pojo.*;
import freemarker.template.Template;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import javax.mail.internet.MimeMessage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.*;

@Component
public class QueueListener {


    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${ego.bigad.categoryId}")
    private long categoryId;

    @DubboReference
    private TBContentDubboService tbContentDubboService;


    @DubboReference
    private TBItemDubboService tbItemDubboService;

    //更新缓存
    @RabbitListener(
            bindings = {@QueueBinding(
                    exchange = @Exchange("${ego.updateBigAdCache.exchange}"),
                    value = @Queue(name = "${ego.updateBigAdCache.queue}",autoDelete = "false"),
                    key = "${ego.updateBigAdCache.routingKey}"
            )}
    )
    public void receiveMessageRedis(Object message){
        System.out.println("message = " + message);

        cacheBigAd();
    }

    public void cacheBigAd() {

        List<TbContent> tbContents = tbContentDubboService.selectTbContentsByCategoryId(categoryId);

        List<BigAd> bigAds = new ArrayList<>();
        //循环大广告集合类容，将TbContent数据获取出来封装成一个个 BigAd 对象
        for (TbContent tbContent : tbContents) {

            BigAd bigAd = new BigAd();
            bigAd.setWidth(670);
            bigAd.setHeight(240);
            bigAd.setSrc(tbContent.getPic());
            bigAd.setSrcB(tbContent.getPic2());
            bigAd.setHref(tbContent.getUrl());
            bigAd.setWidthB(550);
            bigAd.setHeightB(240);
            bigAd.setAlt("");

            //将广告对象添加到集合中
            bigAds.add(bigAd);
        }

        String json = JsonUtils.objectToJson(bigAds);
        System.out.println("json = " + json);

        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("com.ego.portal::bigad",json);
    }



    //更新Solr
    @RabbitListener(
            bindings = {@QueueBinding(
                    exchange = @Exchange("${ego.operation.exchange}"),
                    value = @Queue(name = "${ego.operation.solrInsertQueue}",autoDelete = "false"),
                    key = "${ego.operation.solrInsertRoutingKey}"
            )}
    )
    public void receiveMessageSolrInsert(String ids){
        System.out.println("id = " + ids);

        //http://localhost:8083/insert?ids=161492468003396

//        Map<String, String> params = new HashMap<>();
//        params.put("ids",ids);
//        HttpClientUtil.doGet("http://localhost:8083/insert",params);
        //Spring框架内置发送Http协议请求对象
        RestTemplate restTemplate = new RestTemplate();
        Integer result = restTemplate.getForObject("http://localhost:8083/insert?ids=" + ids, Integer.class);





        //更新商品详情缓存  123123123,123123213
        String[] idArr = ids.split(",");
        for (String id : idArr) {

            TbItem tbItem = tbItemDubboService.selectById(Long.valueOf(id));



            TbItemDetail tbItemDetail = new TbItemDetail();

            //将TbItem对象数据copy到TbItemDetail
            BeanUtils.copyProperties(tbItem,tbItemDetail);

            tbItemDetail.setImages(StringUtils.isNoneBlank(tbItem.getImage())?tbItem.getImage().split(","):new String[1]);


            //缓存数据
            redisTemplate.opsForValue().set("com.ego.item::itemDetail::"+id,tbItemDetail);

        }

    }



    //删除Solr
    @RabbitListener(
            bindings = {@QueueBinding(
                    exchange = @Exchange("${ego.operation.exchange}"),
                    value = @Queue(name = "${ego.operation.solrDeleteQueue}",autoDelete = "false"),
                    key = "${ego.operation.solrDeleteRoutingKey}"
            )}
    )
    public void receiveMessageSolrDelete(String ids){
        System.out.println("删除，下架 = " + ids);

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getForObject("http://localhost:8083/delete?ids=" + ids, Integer.class);


        //更新商品详情缓存  123123123,123123213
        String[] idArr = ids.split(",");
        for (String id : idArr) {

            TbItem tbItem = tbItemDubboService.selectById(Long.valueOf(id));

            //缓存数据
            redisTemplate.delete("com.ego.item::itemDetail::"+id);

        }


    }


    @DubboReference
    private TbOrderDubboService tbOrderDubboService;




    //新增订单
    @RabbitListener(
            bindings = {@QueueBinding(
                    exchange = @Exchange("${ego.operation.exchange}"),
                    value = @Queue(name = "${ego.trade.insertOrderQueue}",autoDelete = "false"),
                    key = "${ego.trade.insertOrderRoutingKey}"
            )}
    )
    //返回数据思路：可以设计一些状态  0，异常 1，库存不足 ，返回订单id就是 成功
    public String insertOrder(Message message){


        try {
            byte[] body = message.getBody();
            InputStream inputStream = new ByteArrayInputStream(body);
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
            OrderPojo orderPojo = (OrderPojo) objectInputStream.readObject();
            System.out.println("orderPojo = " + orderPojo);
            /**
             * orderPojo = OrderPojo{paymentType=1, payment='598117.50',
             * orderShipping=TbOrderShipping [Hash = 170426134, orderId=null, receiverName=smallming, receiverPhone=null, receiverMobile=15891588888, receiverState=北京, receiverCity=北京, receiverDistrict=昌平区, receiverAddress=西三旗 xxxxxxxxx, receiverZip=100000, created=null, updated=null, serialVersionUID=1],
             * orderItems=[TbOrderItem [Hash = 408248948, id=null, itemId=161423327695334, orderId=null, num=6, title=天龙八部, price=1000, totalFee=6000, picPath=http://192.168.126.20:8888/group1/M00/00/00/wKh-FGAvN_iAQWuxAACEjGR9XeE483.jpg, serialVersionUID=1], TbOrderItem [Hash = 1210178618, id=null, itemId=143771107896810, orderId=null, num=5, title=射雕英雄传, price=1150, totalFee=5750, picPath=http://192.168.126.20:8888/group1/M00/00/00/wKh-FGAvQtSAK3-mAADJ0q_pyCs217.jpg, serialVersionUID=1], TbOrderItem [Hash = 582335787, id=null, itemId=536563, orderId=null, num=2, title=new2 - 阿尔卡特 (OT-927) 炭黑 联通3G手机 双卡双待, price=29900000, totalFee=59800000, picPath=http://192.168.126.20:8888/group1/M00/00/00/wKh-FGAvRGuAW3wOAAItIjfWc9U226.jpg, serialVersionUID=1]]}
             */
            //获取订单对象的数据，调用新增订单功能

            //生成订单ID；
            String orderId = IDUtils.genItemId()+"";
            //创建时间
            Date now = new Date();
            //创建订单对象
            TbOrder tbOrder = new TbOrder();
            tbOrder.setOrderId(orderId);
            tbOrder.setPayment(orderPojo.getPayment());
            tbOrder.setPaymentType(orderPojo.getPaymentType());
            tbOrder.setCreateTime(now);
            tbOrder.setUpdateTime(now);

            //获取订单商品，并关联订单
            List<TbOrderItem> orderItems = orderPojo.getOrderItems();
            //循环，设置商品订单id
            for (TbOrderItem orderItem : orderItems) {
                orderItem.setId(IDUtils.genItemId()+"");//此id数据设计理论没有大大意义
                orderItem.setOrderId(orderId);
                //根据购买的商品id去数据查询出对应的商品信息（需要库存比对）
                TbItem tbItem = tbItemDubboService.selectById(Long.valueOf(orderItem.getItemId()));
                //判断购买数量是否小于库存
                if(orderItem.getNum()>tbItem.getNum()){
                    return "1";
                }
            }

            //获取收货地址，并关联订单
            TbOrderShipping orderShipping = orderPojo.getOrderShipping();
            orderShipping.setOrderId(orderId);
            orderShipping.setCreated(now);
            orderShipping.setUpdated(now);


            //执行新增方法
            int row = tbOrderDubboService.insert(tbOrder, orderItems, orderShipping);

            if(row==1){
                return orderId;
            }
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (DaoException e) {
            e.printStackTrace();
            return "0";
        }
        return "0";
    }



    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private FreeMarkerConfig freeMarkerConfig;

    @Value("${spring.mail.username}")
    private String username;


    //删除当前用户购物车中购买过的商品和发送邮件
    @RabbitListener(
            bindings = {@QueueBinding(
                    exchange = @Exchange("${ego.operation.exchange}"),
                    value = @Queue(name = "${ego.trade.sendMailQueue}",autoDelete = "false"),
                    key = "${ego.trade.sendMailRoutingKey}"
            )}
    )
    public void removeCartAndSend(String orderIdAndEmail){


        System.out.println("removeCartAndSend.orderId = " + orderIdAndEmail);
        // //161535846128986:lili@email.com
        String[] orderIdAndEmailArr = orderIdAndEmail.split(":");
        String orderId = orderIdAndEmailArr[0];
        String email = orderIdAndEmailArr[1];

        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();

            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, false, "utf-8");

            //发送者
            helper.setFrom(username);

            //接受者:当前登录用户
            helper.setTo(email);

            //发送标题
            helper.setSubject("易购订单通知");


            Map<String,Object> param = new HashMap<>();
            param.put("orderId",orderId);

            Template template = freeMarkerConfig.getConfiguration().getTemplate("sendMail.ftlh");


            String htmlString = FreeMarkerTemplateUtils.processTemplateIntoString(template, param);

            //发送内容
            helper.setText(htmlString,true);
            //发送邮件
            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
